package http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;

public class TestServerHander extends SimpleChannelInboundHandler<HttpObject> {
    //读取事件
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject httpObject) throws Exception {
        if (httpObject instanceof HttpRequest){
            System.out.println("管道hash:"+channelHandlerContext.pipeline().hashCode() + "   处理器地址："+ this.hashCode());
            System.out.println("httpObject  类型" + httpObject.getClass());
            System.out.println("客户端地址" + channelHandlerContext.channel().remoteAddress());
            //对特定的资源过滤
            HttpRequest httpRequest = (HttpRequest)httpObject;
            URI uri = new URI(httpRequest.uri());
            if ("/favicon.ico".equals(uri.getPath())){
                System.out.println("请求了favicon.ico，不做回应。");
                return;
            }
            //回复给客户端
            ByteBuf byteBuf = Unpooled.copiedBuffer("hello 客户端", CharsetUtil.UTF_8);
            //构建一个http的相应
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, byteBuf);
            response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH,byteBuf.readableBytes());
            //将构建好的response返回
            channelHandlerContext.writeAndFlush(response);
        }
    }
}
